package com.sunlands.qdcy.tongzhuo.web;

import com.sunlands.qdcy.tongzhuo.common.annotation.AutoLog;
import com.sunlands.qdcy.tongzhuo.exception.GlobalExceptionHandler;
import com.sunlands.qdcy.tongzhuo.model.DicDO;
import com.sunlands.qdcy.tongzhuo.model.DicDataDO;
import com.sunlands.qdcy.tongzhuo.service.DicServiceImpl;
import com.sunlands.qdcy.tongzhuo.vo.BusinessResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.sunlands.qdcy.tongzhuo.common.annotation.AutoLog.Level.DEBUG;

/**
 * @author anjl
 * @date 1:35 PM 2019/4/15
 * description:
 */
@SuppressWarnings("unused")
@Api(tags = "11、字典信息")
@ApiResponses(value = {@ApiResponse(code = 400, response = GlobalExceptionHandler.class, message = "数据校验失败"), @ApiResponse(code = 500, response = GlobalExceptionHandler.class, message = "内部错误")})
@Slf4j
@Configuration
@RestController
@RequestMapping("/dic")
public class DicController  {

    private final String token = "!Q@W#E$R%T^Y";

    @ApiOperation(value = "获取字典")
    @AutoLog(logLevel = DEBUG)
    @GetMapping("/{code}")
    public BusinessResult<DicDO> find(@PathVariable String code) {
        DicDO dicDO = dicService.findByCode(code.toUpperCase());
        List<DicDataDO> collect = dicDO.getDicDataSet().stream().sorted(Comparator.comparing(DicDataDO::getSeq)).collect(Collectors.toList());
        dicDO.setDicDataSet(collect);
        return BusinessResult.createSuccessInstance(dicDO);
    }

    @ApiOperation(value = "清空全部")
    @AutoLog
    @GetMapping("/clearAll")
    public BusinessResult<Void> clear(@RequestParam String token, @RequestParam String code){
        if(token.equals(token)){
            if(StringUtils.isNotBlank(code)){
                dicService.findByCode(code);
            }
            dicService.clearCache();
        }
        return BusinessResult.createSuccessInstance(null);
    }

    @Autowired
    private DicServiceImpl dicService;
}
